import {login as loginAPI} from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {constantRoutes,asyncRoutes,anyRoutes} from '@/router/routes'
import {cloneDeep} from 'lodash'
import  router from '@/router/index'

// 过滤路由方法
const filterHandler = (asyncRoutes,routes)=>{
  const filterRoutes = asyncRoutes.filter(route=>{
    if(route.children&&route.children.length){
      route.children = filterHandler(route.children,routes)
    }
    return routes.includes(route.name)
  })
  return filterRoutes
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',   
    roles: [],
    buttons: [],
    routes: [], // 本用户所有的路由,包括了固定的路由和下面的addRouters
    asyncRoutes: [] // 本用户的角色赋予的新增的动态路由
  }
}

const state = getDefaultState()

const mutations = {
  SET_USER: (state, userInfo) => {
    state.name = userInfo.name // 用户名
    state.avatar = userInfo.avatar // 头像
    state.roles = userInfo.roles // 角色列表
    state.buttons = userInfo.buttons // 按钮权限列表
  },

  SET_TOKEN (state, token) {
    state.token = token
  },

  RESET_USER (state) {
    // Object.assign(state, getDefaultState())
    state.token=''
    state.name= ''
    state.avatar= ''
    state.roles= []
    state.buttons=[]
    state.routes=[]
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginAPI.login(username, password)
        .then(result => {
          const { data } = result
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const {data} = await loginAPI.getInfo()
    commit('SET_USER', data)
    // // console.log(data.routes);
    // 过滤用户所需要的路由
    const filterRoutes = filterHandler(cloneDeep(asyncRoutes),data.routes)
    // 用户所拥有的总路由
    const allRoutes = constantRoutes.concat(filterRoutes,anyRoutes)
    // 动态注册路由
    router.addRoutes(allRoutes)

    state.routes = allRoutes

  },

  /* 
  重置用户信息
  */
  async resetUser({ commit, state }) {
    
      await loginAPI.logout()

    // 提交重置用户信息的mutation
    commit('RESET_USER')
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}